<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/5/28 0028
 * Time: 下午 3:23
 */
namespace app\index\controller;
use Workerman\Worker;
use app\index\controller\Base;
class WorkerMan extends base{


    public $c_arrs=[];
    function index(){
        //require_once '../vendor/workerman/workerman-for-win/Autoloader.php';

        $worker = new Worker('websocket://0.0.0.0:8082');// 连接回调
        //var_dump($worker);
        $worker->onConnect = function ($connection){
            //var_dump( $connection);
            //echo "connection success\n";

        };
// 接受发送消息
        $worker->onMessage = function ($conn,$data){
            //var_dump($data);
            $d_arr=json_decode($data,true);
            //var_dump($d_arr);
            if($d_arr['type']==1){
                $this->c_arrs[]=['con'=>$conn,'user_id'=>$d_arr['user_id'],'user_id2'=>$d_arr['user_id2']];
            }elseif($d_arr['type']==2){
                //var_dump($d_arr);
                //var_dump($this->c_arrs);

                foreach($this->c_arrs as $k=>$v){
                    if($v['user_id']==$d_arr['user_id'] && $v['user_id2']==$d_arr['user_id2']){
                        $v['con']->send("请更新数据,用户ID1:{$v['user_id']},用户ID2:{$v['user_id2']}");
                    }
                    if($v['user_id']==$d_arr['user_id2'] && $v['user_id2']==$d_arr['user_id']){
                        $v['con']->send("请更新数据,用户ID1:{$v['user_id']},用户ID2:{$v['user_id2']}");
                    }

                }

            }
            //$conn->send("Hello World");
        };
// 关闭连接
        $worker->onClose = function ($connection){
            echo "connection close \n";
        };
        $worker::runAll();

    }

}